<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\crontab\controller;

use cmf\controller\RestBaseController;

class TongjiController extends RestBaseController
{
    function site_run()
    {
        ini_set('memory_limit', '1280M');
        set_time_limit(0);
        ignore_user_abort(TRUE);
        $cl_id = db('crontab_log')->insertGetId([
            'run_name' => '百度统计定时获取',
            'start_time' => time(),
        ]);

        vendor('baidu/LoginService');
        $loginService = new \LoginService(config('LOGIN_URL'), config('UUID'));
        $ret = $loginService->doLogin(config('USERNAME'), config('PASSWORD'), config('TOKEN'), config('API_URL'));
        if ($ret) {
            $reportService = $loginService->getReportService();

            $sites = db('sites')->select()->toArray();
            foreach ($sites as $site) {

                $siteinfo = db('sites_info')->where(['site_id' => $site['id']])->order('start_time desc')->find();
                if($siteinfo['start_time'] > strtotime(date('Y-m-d',strtotime('-1 day')))) {
                    continue;
                }

                $start_index = 0;
                $arr = [];
                while (true) {
                    $ret = $reportService->getData(array(
                        'site_id' => $site['site_id'],                   //站点ID
                        'method' => 'trend/latest/a',             //趋势分析报告
                        'end_date' => date('Ymd'),             //所查询数据的起始日期
                        'start_date' => date('Ymd',strtotime('-1 day')),             //所查询数据的起始日期
                        'max_results' => 100,                     //返回所有条数
                        'start_index' => $start_index,                        //按天粒度
                    ));
                    $start_index += 300;
                    $data = $ret['body']['data'][0]['result']['items'];
                    if (!$data[0]) {
                        break;
                    }
                    foreach ($data[0] as $key => $value) {
                        $a = [
                            'site_id' => $site['id'],
                            'start_time' => strtotime($data[1][$key][0]),
                            'area' => $data[1][$key][1],
                            'access_page' => $data[1][$key][3],
                            'searchword' => $data[1][$key][4],
                            'ip' => $data[1][$key][5],
                            'visitor_id' => $data[1][$key][6],
                            'visit_time' => $data[1][$key][7],
                            'visit_pages' => $data[1][$key][8],
                            'source_type' => $data[1][$key][2]['fromType'],
                            'source_url' => $data[1][$key][2]['url'] ?? '',
                            'visitor_status' => $value[0]['detail']['visitorStatus'],
                            'visitor_frequency' => $value[0]['detail']['visitorFrequency'],
                            'visitor_type' => $value[0]['detail']['visitorType'],
                            'os' => $value[0]['detail']['os'],
                            'os_type' => $value[0]['detail']['osType'],
                            'ip_status' => $value[0]['detail']['ipStatus'],
                            'end_page' => $value[0]['detail']['endPage'],
                            'isp' => $value[0]['detail']['isp'],
                            'browser_type' => $value[0]['detail']['browserType'],
                            'flash' => $value[0]['detail']['flash'],
                            'cookie' => $value[0]['detail']['cookie'],
                            'java' => $value[0]['detail']['java'],
                            'resolution' => $value[0]['detail']['resolution'],
                            'color' => $value[0]['detail']['color'],
                            'device_type' => $value[0]['detail']['deviceType'],
                            'user_id' => $value[0]['detail']['userId'],
                            'browser' => $value[0]['detail']['browser'],
                            'last_visit_time' => strtotime($value[0]['detail']['lastVisitTime']),
                            'from_type' => $value[0]['detail']['fromType']['fromType'],
                            'from_type_url' => $value[0]['detail']['fromType']['url'] ?? '',
                        ];
                        foreach ($value[0]['detail']['paths'] as $paths) {
                            $a['paths'][] = [
                                'time' => strtotime($paths[0]),
                                'second' => $paths[1],
                                'url' => $paths[2],
                            ];
                        }
                        if (!in_array($a, $arr)) {
                            $arr[] = $a;
                        }
                    }
                    if (count($data[0]) < 300) {
                        break;
                    }
                }

                foreach (array_reverse($arr) as $data) {
                    $val = $data;
                    unset($val['paths']);
                    $val['site_id'] = $site['id'];
                    $val['visitor_type'] = $val['visitor_type'] == '老访客' ? 1 : 0;
                    $val['flash'] = $val['flash'] ? 1 : 0;
                    $val['cookie'] = $val['cookie'] ? 1 : 0;
                    $val['java'] = $val['java'] ? 1 : 0;
                    if(strpos($val['source_type'],'http') === 0){
                        $val['source_type'] = '外链';
                    }
                    if(strpos($val['from_type'],'http') === 0){
                        $val['from_type'] = '外链';
                    }
                    $id = db('sites_info')->insertGetId($val);
                    $paths = [];
                    foreach ($data['paths'] as $path) {
                        $path['pid'] = $id;
                        $paths[] = $path;
                    }
                    db('sites_info_paths')->insertAll($paths);
                }
            }
            db('crontab_log')->where("id=$cl_id")->update([
                'end_time' => time(),
            ]);
            $this->success('更新成功！');
        } else {
            db('crontab_log')->where("id=$cl_id")->update([
                'end_time' => time(),
            ]);
            $this->error('api接口错误');
        }
    }
}
